package com.lgm.ht.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lgm.ht.exception.BusException;
import com.lgm.ht.mapper.FruitMapper;
import com.lgm.ht.pojo.Type;
import com.lgm.ht.dto.TypeDTO;
import com.lgm.ht.mapper.TypeMapper;
import com.lgm.ht.service.FruitService;
import com.lgm.ht.service.TypeService;
import com.lgm.ht.utils.ResultModel;
import com.lgm.ht.vo.TypeVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
public class TypeServiceImpl implements TypeService {

 final private TypeMapper typeMapper;
 final private FruitService fruitService;

 @Override
 public ResultModel<List<TypeVO>> find(TypeDTO typeDTO) {

     List<TypeVO> typeVOList = new ArrayList<>();


     QueryWrapper queryWrapper = new QueryWrapper();
     queryWrapper.eq("shop_id",typeDTO.getShopId());

     List<Type> typeList = typeMapper.selectList(queryWrapper);

     for(Type type : typeList){
         TypeVO typeVO = new TypeVO();
         typeVO.setId(type.getId());
         typeVO.setName(type.getName());
         typeVOList.add(typeVO);
     }
     return ResultModel.success("查询type成功",2,typeVOList);
 }

    @Override
    public ResultModel add(TypeDTO typeDTO) {

        Type type = new Type();
        type.setName(typeDTO.getName());
        type.setShopId(typeDTO.getShopId());

        typeMapper.insert(type);

        return ResultModel.success("添加成功",null);
    }

    @Override
    public ResultModel update(int id, TypeDTO typeDTO) {

        Type type = new Type();
        type.setId(id);
        type.setName(typeDTO.getName());

        typeMapper.updateById(type);

        return ResultModel.success("更新成功");
    }

    @Override
    public ResultModel deleteById(int id) {
        long count = fruitService.findCountByType(id);
        if(count>0){
            throw new BusException("当前分类下还有水果信息,请先删除水果后再删除分类");
        }

        typeMapper.deleteById(id);
        return ResultModel.success("删除成功");
    }
}
